<template>
    <div>
        <el-dialog
            width="70%"
            :title="!form.id ? '新增' : `修改-【${projectName}】`"
            :visible.sync="visible"
            @closed="handleDialogClose"
            :close-on-click-modal="false">
            <el-form v-loading="loadingDialog" element-loading-text="给我一点时间" ref="form" class="form_wrap" :model="form" :inline="false" :rules="rules" @click="handleSubmit()" label-width="120px">
                <el-tabs class="project_tabs" v-model="activeTab" type="card">

                    <el-tab-pane name="projectInfo">
                        <span slot="label"><i class="el-icon-document"></i> 项目信息</span>

                        <div class="form_scroll_wrap" ref="project_info_dialog_wrap">
                            <el-row>
                                <el-col :span="12">
                                    <el-form-item label="项目名称" prop="name">
                                        <el-input placeholder="" v-model="form.name" clearable style="width: 80%"></el-input>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="12">
                                    <el-form-item label="项目编码" prop="code">
                                        <el-input placeholder="" v-model="form.code" clearable style="width: 80%"></el-input>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="12">
                                    <el-form-item label="开始时间" prop="startDate">
                                        <el-date-picker
                                            v-model="form.startDate"
                                            type="date"
                                            placeholder="选择日期"
                                            value-format="yyyy-MM-dd"
                                            style="width: 80%;">
                                        </el-date-picker>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="12">
                                    <el-form-item label="结束时间" prop="endDate">
                                        <el-date-picker
                                            v-model="form.endDate"
                                            type="date"
                                            placeholder="选择日期"
                                            value-format="yyyy-MM-dd"
                                            style="width: 80%;">
                                        </el-date-picker>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="12">
                                    <el-form-item label="部门名称" prop="deptId">
                                        <DeptCascader
                                            ref="cascader_dept"
                                            :cascaderDeptVal.sync="cascaderDeptVal"
                                            :checkStrictly="true"
                                            :clearable="false"
                                            styles="width: 80%">
                                        </DeptCascader>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="12">
                                    <!-- <el-form-item label="部门经理" prop="deptOwnerName">
                                        <el-input
                                            placeholder="选择员工..."
                                            :disabled="true"
                                            v-model="form.deptOwnerName"
                                            style="width: 80%">
                                            <i slot="prefix" class="el-input__icon el-icon-search choose_search_icon" @click="handleEmpDeptDialogVisible('deptMgr')"></i>
                                            <i slot="suffix" class="el-input__icon el-icon-close choose_clear_icon" @click="handleClearDeptOwner"></i>
                                        </el-input>
                                    </el-form-item> -->
                                    <el-form-item label="部门经理" prop="deptOwnerName">
                                        <el-input placeholder="请选择..." :disabled="true" v-model="form.deptOwnerName" style="width: 80%">
                                            <el-button @click="handleEmpDeptDialogVisible('deptMgr')" slot="append" icon="el-icon-search" class="choose_emp_btn">关联员工</el-button>
                                            <el-button @click="handleClearDeptOwner" slot="append" icon="el-icon-close" class="del_emp_btn"></el-button>
                                        </el-input>
                                    </el-form-item>

                                </el-col>
                                <el-col :span="12">
                                    <!-- <el-form-item label="项目经理" prop="projectMgrName">
                                        <el-input
                                            placeholder="选择员工..."
                                            :disabled="true"
                                            v-model="form.projectMgrName"
                                            style="width: 80%">
                                            <i slot="prefix" class="el-input__icon el-icon-search choose_search_icon" @click="handleEmpDeptDialogVisible('projectMgr')"></i>
                                            <i slot="suffix" class="el-input__icon el-icon-close choose_clear_icon" @click="handleClearProjectMgr"></i>
                                        </el-input>
                                    </el-form-item> -->
                                    <el-form-item label="项目经理" prop="projectMgrName">
                                        <el-input placeholder="请选择..." :disabled="true" v-model="form.projectMgrName" style="width: 80%">
                                            <el-button @click="handleEmpDeptDialogVisible('projectMgr')" slot="append" icon="el-icon-search" class="choose_emp_btn">关联员工</el-button>
                                            <el-button @click="handleClearProjectMgr" slot="append" icon="el-icon-close" class="del_emp_btn"></el-button>
                                        </el-input>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="12">
                                    <el-form-item label="项目状态" prop="status">
                                        <el-select v-model="form.status" placeholder="请选择" style="width: 80%">
                                            <el-option label="立项" :value="0"></el-option>
                                            <el-option label="审批" :value="1"></el-option>
                                            <el-option label="进行" :value="2"></el-option>
                                            <el-option label="挂起" :value="3"></el-option>
                                            <el-option label="结束" :value="4"></el-option>
                                        </el-select>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="24">
                                    <el-form-item label="项目描述" prop="description">
                                        <Wangeditor ref="editorRefs" :htmlVal.sync="form.description" :visible="visible" height="300" style="width: 91%" />
                                    </el-form-item>
                                </el-col>
                                <el-col :span="24">
                                    <el-form-item label="项目备注" prop="remarks">
                                        <Wangeditor ref="editorRefs" :htmlVal.sync="form.remarks" :visible="visible" height="300" style="width: 91%" />
                                    </el-form-item>
                                </el-col>
                                <!-- <el-col :span="24">
                                    <el-form-item label="项目备注" prop="remarks">
                                        <el-input v-model="form.remarks" type="textarea" :rows="4" clearable placeholder="备注..." style="width: 91.5%;"></el-input>
                                    </el-form-item>
                                </el-col> -->
                                <!-- <el-col :span="24">
                                    <el-form-item label="项目描述" prop="description">
                                        <el-input v-model="form.description" type="textarea" :rows="4" clearable placeholder="备注..." style="width: 91.5%;"></el-input>
                                    </el-form-item>
                                </el-col> -->
                            </el-row>


                        </div>
                    </el-tab-pane>

                    <el-tab-pane name="devList">
                        <span slot="label"><i class="el-icon-s-custom"></i> 开发人员设置</span>

                        <div class="form_scroll_wrap" ref="dev_list_dialog_wrap">
                            <div class="dev_btns">
                                <div class="left">
                                    <el-alert
                                        show-icon
                                        title="未设置开发人员【角色，开发周期】的数据将不被提交"
                                        type="warning" :closable="false">
                                    </el-alert>
                                </div>
                                <div class="right">
                                    <el-button @click="handleEmpDeptDialogVisible('devEmps')" type="primary" plain icon="el-icon-plus" size="small">添加开发人员</el-button>
                                    <el-button @click="handleDevInfoVisible" icon="el-icon-setting" type="primary" plain size="small">设置开发人员信息</el-button>
                                </div>
                            </div>
                            <!-- 表格 -->
                            <el-table
                                class="mt10"
                                ref="table"
                                size="medium"
                                height="400"
                                empty-text="暂无数据"
                                element-loading-text="给我一点时间"
                                fit border highlight-current-row
                                :stripe="stripe"
                                v-loading="loadingDataList"
                                :data="dataList"
                                @selection-change="handleSelection">

                                <el-table-column type="selection" width="55" prop="selection" align="center"></el-table-column>
                                <el-table-column label="工号" prop="empWorkNo" width="80" align="left" fixed show-overflow-tooltip/>
                                <el-table-column label="名称" prop="empName" width="100" align="left" fixed show-overflow-tooltip/>
                                <el-table-column label="状态" prop="status" align="center" width="80px" show-overflow-tooltip>
                                    <template slot-scope="scope">
                                        <el-link v-if="scope.row.status == '0'" type="success" :underline="false">进行中</el-link>
                                        <el-link v-else-if="scope.row.status == '1'" type="danger" :underline="false">已结束</el-link>
                                    </template>
                                </el-table-column>
                                <el-table-column label="部门" prop="deptName" width="150" align="left" show-overflow-tooltip/>
                                <el-table-column label="岗位" prop="postName" width="140" align="left" show-overflow-tooltip/>
                                <el-table-column label="项目角色" prop="projectRole" width="100" align="left" show-overflow-tooltip/>
                                <el-table-column label="开始时间" prop="startDate" width="120" align="left" show-overflow-tooltip/>
                                <el-table-column label="结束时间" prop="endDate" width="120" align="left" show-overflow-tooltip/>
                                <el-table-column label="平时加班" prop="workNormal" align="center" show-overflow-tooltip/>
                                <el-table-column label="周末加班" prop="workWeekend" align="center" show-overflow-tooltip/>
                                <el-table-column label="节日加班" prop="workHoliday" align="center" show-overflow-tooltip/>

                                <el-table-column label="操作" prop="btn" v-if="isHideColumn('btn')" width="80px" align="center" fixed="right">
                                    <template slot-scope="scope">
                                        <el-button @click="handleDeleteDevs(scope.row, scope.$index)" type="text" size="small">删除</el-button>
                                    </template>
                                </el-table-column>

                            </el-table>
                        </div>
                    </el-tab-pane>
                </el-tabs>
            </el-form>

            <div slot="footer" class="dialog-footer">
                <el-button @click="visible = false">取 消</el-button>
                <el-button @click="handleSubmit()" type="primary" :submitLoading="submitLoading">提 交</el-button>
            </div>

            <el-dialog
                width="30%"
                title="设置开发人员信息"
                :visible.sync="devInfoVisible"
                append-to-body>

                    <el-form ref="formDevInfo" :model="formDevInfo" :rules="rulesDevInfoSetting" label-width="120px">
                        <el-form-item label="项目角色" prop="projectRole">
                            <DictSelect ref="select" code="ProjectRole" :selectVal.sync="formDevInfo.projectRole" styles="width:80%"></DictSelect>
                        </el-form-item>
                        <el-form-item label="开始时间" prop="startDate">
                            <el-date-picker
                                clearable style="width: 80%"
                                v-model="formDevInfo.startDate"
                                type="date"
                                placeholder="选择日期"
                                value-format="yyyy-MM-dd">
                            </el-date-picker>
                        </el-form-item>
                        <el-form-item label="结束时间" prop="endDate">
                            <el-date-picker
                                clearable style="width: 80%"
                                v-model="formDevInfo.endDate"
                                type="date"
                                placeholder="选择日期"
                                value-format="yyyy-MM-dd">
                            </el-date-picker>
                        </el-form-item>
                        <el-form-item label="平时加班" prop="workNormal">
                            <el-input-number placeholder="小时" v-model="formDevInfo.workNormal" :precision="1" :step="0.1" style="width: 80%"></el-input-number>
                        </el-form-item>
                        <el-form-item label="周末加班" prop="workWeekend">
                            <el-input-number placeholder="小时" v-model="formDevInfo.workWeekend" :precision="1" :step="0.1" style="width: 80%"></el-input-number>
                        </el-form-item>
                        <el-form-item label="节日加班" prop="workHoliday">
                            <el-input-number placeholder="小时" v-model="formDevInfo.workHoliday" :precision="1" :step="0.1" style="width: 80%"></el-input-number>
                        </el-form-item>
                        <el-form-item label="开发状态" prop="status">
                            <el-select v-model="formDevInfo.status" placeholder="请选择" style="width: 80%">
                                <el-option label="进行中" value="0"></el-option>
                                <el-option label="已结束" value="1"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-form>

                    <div slot="footer" class="dialog-footer">
                        <el-button @click="devInfoVisible = false">取 消</el-button>
                        <el-button @click="handleSettingDevInfo" type="primary">提 交</el-button>
                    </div>
            </el-dialog>

        </el-dialog>

        <!-- 员工查询窗口 -->
        <EmpDeptDialog
            ref="EmpDeptDialog"
            :multiple="multiple"
            :triggerEvent="triggerEvent"
            @deptMgr="handleDeptOwnerMgr"
            @projectMgr="handleProjectMgr"
            @devEmps="handleDevEmps" />
    </div>
</template>

<script>
    import DeptCascader from '@/views/hr/dept/components/edit-dept-cascader'
    import DictSelect from '@/views/system/sysdict/components/dict-select'
    import EmpDeptDialog from '@/views/hr/employee/components/EmpDeptDialog'
    import Wangeditor from '@/views/components/wangeditor'
    import TableMixin from '@/mixin/TableMixin'

    export default {
        mixins: [TableMixin],
        components: {
            DeptCascader,
            DictSelect,
            EmpDeptDialog,
            Wangeditor
        },
        data() {
            return {
                visible: false,
                devInfoVisible: false,
                submitLoading: false,
                activeTab: 'projectInfo',
                projectName: null,
                loadingDialog: false,
                loadingDataList: false,
                form: {
                    id: null,
                    deptId: null,
                    deptName: null,
                    deptOwnerId: null,
                    deptOwnerName: null,
                    projectMgrId: null,
                    projectMgrName: null,
                    name: null,
                    code: null,
                    startDate: null,
                    endDate: null,
                    status: null,
                    remarks: null,
                    description: null
                },
                rules: {
                    deptOwnerName: [{required: true, message: '部门经理不能为空', trigger: 'blur'}],
                    projectMgrName: [{required: true, message: '项目经理不能为空', trigger: 'blur'}],
                    name: [{required: true, message: '项目名称不能为空', trigger: 'blur'}],
                    code: [{required: true, message: '项目编码不能为空', trigger: 'blur'}],
                    startDate: [{required: true, message: '项目开始时间不能为空', trigger: 'blur'}],
                    endDate: [{required: true, message: '项目结束时间不能为空', trigger: 'blur'}],
                    status: [{required: true, message: '项目状态不能为空', trigger: 'blur'}],
                },
                rulesDevInfoSetting: {
                    projectRole: [{required: true, message: '项目角色不能为空', trigger: 'blur'}],
                    startDate: [{required: true, message: '员工开发起始时间不能为空', trigger: 'blur'}],
                    endDate: [{required: true, message: '员工开发结束时间不能为空', trigger: 'blur'}],
                    workNormal: [{required: true, message: '平时加班（小时）不能为空', trigger: 'blur'}],
                    workWeekend: [{required: true, message: '周末加班（小时）不能为空', trigger: 'blur'}],
                    workHoliday: [{required: true, message: '节日前加班（小时）不能为空', trigger: 'blur'}],
                    status: [{required: true, message: '状态不能为空', trigger: 'blur'}]
                },

                // 部门下拉级联
                cascaderDeptVal: [],
                // 员工选择
                triggerEvent: null,
                // 部门数据
                deptData: null,
                // 选择员工(单选/多选)
                multiple: false,
                // 富编辑器
                htmlVal: null,

                // 开发人员表格数据
                dataList: [],
                empObj: {
                    identity: null,
                    deptId: null,
                    deptName: null,
                    postId: null,
                    postName: null,
                    empId: null,
                    empWorkNo: null,
                    empName: null,
                    projectRole: null,
                    startDate: null,
                    endDate: null,
                    workNormal: null,
                    workWeekend: null,
                    workHoliday: null,
                    status: '0'
                },
                formDevInfo: {
                    projectRole: null,
                    startDate: null,
                    endDate: null,
                    workNormal: null,
                    workWeekend: null,
                    workHoliday: null,
                    status: '0'
                }
            }
        },
        watch: {
            cascaderDeptVal(val) {
                //监听到路径变化需要查出这个三级分类的分组信息
                this.form.deptId = val[val.length - 1];

                setTimeout(() => {
                    // 需要有时间延迟，才能获取值（需等待渲染完成）
                    this.deptData = this.$refs.cascader_dept.dataVal

                    // 自动填充部门经理
                    // if(this.deptData != null && this.form.deptOwnerName == null || this.form.deptOwnerName === '') {
                    //     this.form.deptOwnerName = this.deptData.ownerEmpName
                    // } else {
                    //     this.form.deptOwnerName = null
                    // }
                }, 1000);
            }
        },

        methods: {
            init(id, projectName) {
                const _this = this
                // 情况表单数据
                this.form.id = id || null
                this.projectName = projectName || null
                this.cascaderDeptVal = []
                this.activeTab = 'projectInfo'
                this.visible = true

                this.loadingDialog = true

                this.$nextTick(() => {
                    _this.$refs['form'].resetFields()
                    this.dataList = []

                    if (this.form.id) {
                        setTimeout(() => {
                            // 获取项目信息
                            this.getInfo(this.form.id)
                        }, 500);
                    } else {
                        this.loadingDialog = false
                    }
                })
            },

            /**
             * 员工查询窗口
             */
            handleEmpDeptDialogVisible(triggerEvent) {
                if(triggerEvent === 'devEmps') {
                    this.multiple = true
                }
                this.triggerEvent = triggerEvent
                // 表单窗口
                this.$nextTick(() => {
                    this.$refs.EmpDeptDialog.show()
                })
            },

            /**
             * 设置开发人员信息
             */
            handleDevInfoVisible() {
                if (this.selectionRows.length <= 0) {
                    this.$notify({title: '提示', message: '请选择需要设置的人员的记录！', type: 'info'});
                } else {
                    this.devInfoVisible = true
                }
            },

            /**
             * 重新设定选中的开发人员信息
             * 角色，开始、结束时间等
             */
            async handleSettingDevInfo() {
                const refs = this.$refs
                const valid = await refs['formDevInfo'].validate().catch(() => {})
                if (valid) {
                    this.selectionRows.forEach(item => {
                        this.dataList = this.dataList.filter((empObj)=>{
                            if(empObj.identity === item.identity) {
                                return Object.assign(empObj, this.formDevInfo)
                            } else {
                                return empObj
                            }
                        })
                    })
                    refs['formDevInfo'].resetFields()
                    this.devInfoVisible = false
                }

            },

            /**
             * 选择员工
             * 开发人员
             * @param {*} data
             */
            handleDevEmps(data) {
                let index = this.dataList.length
                if(data && data.length > 0) {
                    data.forEach(item => {
                        this.empObj = Object.assign({}, this.empObj, {
                            identity: index+'-'+item.id, // 标识，用于修改某行数据
                            projectId: (this.form.id ? this.form.id : null),
                            deptId: item.deptId,
                            deptName: item.deptName,
                            postId: item.postId,
                            postName: item.postName,
                            empId: item.id,
                            empWorkNo: item.workNo,
                            empName: item.name,
                            workNormal: 0,
                            workWeekend: 0,
                            workHoliday: 0
                        })
                        this.dataList.push(this.empObj)
                        index++
                    })
                }
            },

            /**
             * 详细信息
             */
            async getInfo(id) {
                if (id) {
                    const res = await this.$http({
                        url: '/pm/project_center/info/detail/' + id,
                        method: 'GET'
                    })
                    this.form = Object.assign({}, res.data)

                    this.cascaderDeptVal = this.form.cascaderDeptPathVals || [];

                    if(this.form.devs && this.form.devs.length > 0) {
                        // 给对象数据添加属性，用于标识修改某行
                        let index = 0
                        this.form.devs.forEach(item => {
                            item['projectId'] = (this.form.id ? this.form.id : null),
                            item['identity'] = index+'-'+item.empId
                            index++
                        })
                        this.dataList = this.form.devs
                    }

                    this.loadingDialog = false
                }
            },

            /**
             * 提交表单
             */
             async handleSubmit() {
                const refs = this.$refs
                this.submitLoading = true
                const valid = await refs['form'].validate().catch(() => {})
                if (valid) {

                    if(this.dataList && this.dataList.length > 0) {
                        // 过滤掉没有设置开发人员角色和开发周期的数据
                        this.dataList = this.dataList.filter(item => {
                            return item.projectRole && item.startDate && item.endDate
                        })
                        this.form['devs'] = this.dataList
                    }

                    const res = await this.$http({
                        url: `/pm/project_center/${!this.form.id ? 'save' : 'update'}`,
                        method: 'POST',
                        data: this.form
                    })
                    if (this.ResultMessage(res)) {
                        this.$emit('refreshDataList')
                        this.submitLoading = false
                        this.visible = false
                    } else {
                        this.submitLoading = false
                    }
                    this.submitLoading = false
                } else {
                    this.submitLoading = false
                }
            },

            /**
             * 选择员工
             * 部门经理
             * @param {*} data
             */
            handleDeptOwnerMgr(data) {
                this.form.deptOwnerId = data[0].id
                this.form.deptOwnerName = data[0].name
            },

            /**
             * 选择员工
             * 项目经理
             * @param {*} data
             */
            handleProjectMgr(data) {
                this.form.projectMgrId = data[0].id
                this.form.projectMgrName = data[0].name
            },

            /**
             * 清空选着（部门经理）
             */
             handleClearDeptOwner() {
                this.form.deptOwnerId = null
                this.form.deptOwnerName = null
            },

            /**
             * 清空选着（项目经理）
             */
             handleClearProjectMgr() {
                this.form.projectMgrId = null
                this.form.projectMgrName = null
            },

            /**
             * 删除[开发人员]
             */
             async handleDeleteDevs(row, index) {
                if(row.id) {
                    let ids = []
                    if (row) {
                        ids.push(row.id)
                    }
                    if (this.selectionRows) {
                        this.selectionRows.filter((item, index) => {
                            ids.push(item.id)
                        })
                    }
                    if (ids.length <= 0) {
                        this.$notify({title: '提示', message: '请选择需要删除的记录！', type: 'info'});
                    } else {
                        const confirm = await this.$confirm('确定要删除？', '提示', {type: 'warning'}).catch(() => {})
                        if (confirm) {
                            const res = await this.$http({
                                url: '/pm/project_dev_emp/delete',
                                method: 'POST',
                                data: ids
                            })
                            if (this.ResultMessage(res)) {
                                this.getDataList()
                            }
                        }
                    }
                } else {
                    // 这个是删除未保存到数据库中的记录
                    this.dataList.splice(index, 1)
                }
            },

            /**
             * 获取表格数据[开发人员]
             */
             async getDataList() {
                this.loadingDataList = true
                const res = await this.$http({
                    url: '/pm/project_dev_emp/list',
                    method: 'GET',
                    params: {
                        sortColumns: 'status',
                        sortType: 'ASC'
                    }
                })
                if (this.ResultMessage(res, false)) {
                    this.dataList = res.data || []

                    // 给对象数据添加属性，用于标识修改某行
                    let index = 0
                    this.dataList.forEach(item => {
                        item['projectId'] = (this.form.id ? this.form.id : null),
                        item['identity'] = index+'-'+item.empId
                        index++
                    })
                }
                this.loadingDataList = false
            },

            handleDialogClose() {
                // 清空子组件editor内容
                this.$refs.editorRefs.clearVal()
            }
        }


    };
</script>

<style lang="scss" scoped>

.form_wrap{
    .project_tabs{
        .el-tabs__header{
            margin: 0;
        }
    }

    .choose_search_icon{
        color: #409EFF;
    }
    .choose_clear_icon{
        color: #F56C6C;
    }

}

.dev_btns{
    display: flex;
    justify-content: space-between;
    align-items: center;
    .left{
        flex: 1;
    }
    .right {
        margin-right: 10px;
        margin-left: 10px;
    }
}
.el-input-group__append{
        .choose_emp_btn{
            color: #409EFF;
        }
        .del_emp_btn{
            color: red;
            border-top-left-radius: 0;
            border-bottom-left-radius: 0;
            border-left: 1px solid #DCDFE6;
        }
    }
</style>
